package net.lulihu.pangolin.headless.common.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

public class ProtocolMessageDecoder extends LengthFieldBasedFrameDecoder {

    //最大包为2M
    private static final int MAX_FRAME_LENGTH = 2 * 1024 * 1024;
    // 长度字段的偏移量
    private static final int LENGTH_FIELD_OFFSET = 0;
    //长度字段的长度
    private static final int LENGTH_FIELD_LENGTH = 4;
    //从解码帧中去除的第一个字节数
    private static final int INITIAL_BYTES_TO_STRIP = 0;
    //要添加到长度字段值的补偿值
    private static final int LENGTH_ADJUSTMENT = 0;

    // 头部大小
    private static final byte HEADER_SIZE = 4;

    public ProtocolMessageDecoder() {
        super(MAX_FRAME_LENGTH, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH, LENGTH_ADJUSTMENT, INITIAL_BYTES_TO_STRIP);
    }

    @Override
    protected ProtocolMessage decode(ChannelHandlerContext ctx, ByteBuf in2) throws Exception {
        ByteBuf in = (ByteBuf) super.decode(ctx, in2);

        if (in == null) {
            return null;
        }

        if (in.readableBytes() < HEADER_SIZE) {
            return null;
        }

        int frameLength = in.readInt();
        if (in.readableBytes() < frameLength) {
            return null;
        }

        ProtocolMessage message = new ProtocolMessage();
        message.setType(in.readByte());

        byte[] data = new byte[frameLength - 1];
        in.readBytes(data);
        message.setBody(data);

        in.release();
        return message;
    }

}
